<template>
    <div>
        <el-input v-model="role" disabled></el-input>
        <el-tree :data="list" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current
            :props="defaultProps" style="margin: 20px 0">
        </el-tree>
        <el-button type="primary" @click="save" :loading="loading">保存</el-button>
        <el-button @click="cancel">取消</el-button>
    </div>
</template>

<script>
export default {
    name: 'roleAuth',
    data() {
        return {
            role: '',
            list: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            loading: false
        }
    },
    created() {
        const roleId = this.$route.params.id
        this.role = this.$route.query.roleName
        this.getData(roleId)
    },
    methods: {
        async getData(roleId) {
            let res = await this.$API.roleAuth.reqGetroleAuth(roleId)
            if (res.code == 20000) {
                this.list = res.data.children
                const checkedIds = this.getCheckedIds(this.list)
                this.$refs.tree.setCheckedKeys(checkedIds)

                this.$refs.tree.getCheckedKeys()
            }
        },
        // 得到所选中的id列表
        getCheckedIds(auths, initArr = []) {
            return auths.reduce((pre, item) => {
                if (item.select && item.level === 4) {
                    pre.push(item.id)
                } else if (item.children) {
                    this.getCheckedIds(item.children, initArr)
                }
                return pre
            }, initArr)
        },
        // 保存权限
        /* 
            vue的elementUI 的tree属性控件：getCheckedKeys只能获取到子节点，getHalfCheckedKeys可以获取到父元素的id
        */
        async save() {
            this.loading = true

            const keys = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()).join(",")
            // const keys = this.$refs.tree.getCheckedKeys().join(",")
            let res = await this.$API.roleAuth.reqSaveroleAuth(this.$route.params.id, keys)
            if (res.code == 20000) {
                this.loading = false
                this.$message({ type: 'success', message: `分配权限成功` })
                this.$router.replace({ name: 'Role' })
            }
        },
        cancel() {
            this.$router.replace({ name: 'Role' })
        }
    }
}
</script>

<style></style>